<?php

namespace App\Http\Controllers\Admin\ExportReportSample;

use Dompdf\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use PhpOffice\PhpWord\IOFactory;
use Storage;
use App\Http\Controllers\Admin\ItemDataController;

class GanSuBaiYinController extends Controller
{
    #需要修改 \PhpOffice\PhpWord\TemplateProcessor()->deleteBlock()->replaceBlock();
    protected $sourceDir = './storage/ExcelTemplate/GanSuBaiYin/';
    private $disk=null;
    private $storeFile='';
    private $download = 0;
    protected static $resCode = [0=>'不合格',1=>'合格',2=>'不合格',3=>'未试验'];

    /**
     * 导出单个样品检测报告,用于二维码扫码后的查看
     * @param Request $request
     * @return string
     * @throws \PhpOffice\PhpWord\Exception\CopyFileException
     * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException
     * @throws \PhpOffice\PhpWord\Exception\Exception
     */
    public function export(Request $request) {

        $sample_id = request('id');
        $this->download = request('down',0);
        $setting = DB::table('setting')->find(1); //
        $report_num_pre = $setting->report_num_pre; //报告编号前缀
        $company_name = $setting->name_rep; //获取检测公司名称
        //程序开始
        $values = [];
        $sample_info = $info = DB::table('a_sample_info as a')
            ->leftJoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')
            ->leftJoin('a_contract as c','a.contract_id','=','c.id')
            ->leftJoin('a_status_time as d','d.contract_id','=','c.id')
            ->where('a.id',$sample_id)
            ->select('a.id','c.entrusted_company','b.tool_name','b.voltage','c.test_kind','a.manufacturer','a.self_num','a.test_time','b.std_num','a.res','a.remark','a.tester_names','a.test_time','a.audit_man','c.audit_man as pi_man','d.sendback_end','b.std_id','b.tool_id','c.created_at as c_create','b.class','b.class_id','b.vol_id','b.item_ids','a.bar_code','a.next_time','c.batchNum','a.guige_xinghao','c.test_address','c.status','c.client_name','b.count','b.unit','c.letter_no','a.batch_num_custom','c.deadline')
            ->first();
        if (!$sample_info) {
            return '样品不存在！';
        }
        $this->storeFile = "reports/$sample_info->batchNum/".$sample_info->bar_code.'.docx';
        $this->disk = Storage::disk('public');
        //文件存在直接下载
        if($this->disk->exists($this->storeFile) && $sample_info->status > 13 && $this->download == 1){
            return $this->disk->download($this->storeFile);
        }

        //加载word模板
        $template_file = "./storage/ExcelTemplate/GanSuBaiYin/{$sample_info->tool_name}.docx"; //考虑到兼容Linux，斜杠用“/”
        if (!file_exists($template_file)) {
            //为了防止内存泄漏，建议用完手动清理
            return "{$sample_info->tool_name}的word模板文件不存在";
        }

        //检验日期开始时间
        $testdate_start = DB::table('a_sample_info as B')->leftJoin('a_item_data as A', 'A.sample_info_id', '=', 'B.id')->where('B.id', $sample_id)->min('test_time');
        //检验日期结束时间
        $testdate_end = DB::table('a_sample_info as B')->leftJoin('a_item_data as A', 'A.sample_info_id', '=', 'B.id')->where('B.id', $sample_id)->max('test_time');
        //试验依据
        $standards = DB::table('a_standard')->where('id',$sample_info->std_id)->first();
        //获取温湿度大气压
        $temp_hum_sqs = "select max(temp) as maxtemp,max(hum) as maxhum,max(pressure) as maxpressure from a_item_data where temp != '' and hum !='' and sample_info_id= ".$sample_id;
        $temp_hum_data = DB::select($temp_hum_sqs);
        //检测设备
        $dev_name = '';
        $fac_num = '';
        $dev_num = '';
        $station_ids = [];
        $test_item_data = DB::table('a_item_data')->where('sample_info_id',$sample_id)->where('item_id','!=',61)->get();
        foreach($test_item_data as $kdev=>$devv){
            $station_ids =array_merge($station_ids,explode(',',$devv->station_ids));
            $station_ids = array_unique($station_ids);
        }
        $devInfo = DB::table('a_station')->whereIn('id',$station_ids)->select('fac_num','dev_num','name')->get()->toArray();
        if($devInfo){
            $dev_name = implode(',',array_column($devInfo,'name'));
            $fac_num = implode(',',array_column($devInfo,'fac_num'));
            $dev_num = implode(',',array_column($devInfo,'dev_num'));
        }

        //签发日期
        if($sample_info->deadline) {
            $year = date('Y', strtotime($sample_info->deadline));
            $month = date('m', strtotime($sample_info->deadline));
            $day = date('d', strtotime($sample_info->deadline));
        }
        //配置参数
        $values = [
            // 'batchNum' => $report_num_pre . $data_batch->batchNum,
            'test_name' => $sample_info->tool_name,
            'batchNum' => $sample_info->batch_num_custom,
            'bar_code' => $sample_info->bar_code,
            'test_guige' => $sample_info->guige_xinghao,
            'entrusted_company' => $sample_info->entrusted_company,
            //'test_addr' => $sample_info->test_address,
            'test_addr' => '中国 甘肃 白银市白银区刘家梁170号',
            'entrustNum'=>$sample_info->letter_no,           //委托编号
            'test_type' => $sample_info->test_kind,
            'company_name'=>$company_name,
            'report_end' => $sample_info->deadline?date('Y年m月d日',strtotime($sample_info->deadline)):'',
            'yp_date'=>date('Y.m.d',strtotime($sample_info->c_create)),
            'test_start_date'=>date('Y.m.d',strtotime($testdate_start)),
            'test_end_date'=>$sample_info->deadline?date('Y.m.d',strtotime($sample_info->deadline)):'',
            'standards'=>$standards->num.'《'.$standards->name.'》',
            'client_name'=>$sample_info->client_name,
            'number'=>$sample_info->count.$sample_info->unit,
            'pressure'=>$temp_hum_data[0]->maxpressure,
            'temp'=>$temp_hum_data[0]->maxtemp,
            'humi'=>$temp_hum_data[0]->maxhum,
            'station_name'=>$dev_name,
            'fac_num'=>$fac_num,
            'dev_num'=>$dev_num,
            'year'=>isset($year)?$year:'',
            'month'=>isset($month)?$month:'',
            'day'=>isset($day)?$day:'',
            'remark'=>'无',
            'sc_date'=>'/',
        ];

        //获取该样品的所有标准下的试验项目id,并去重
        $allItemId_arr = [];
        $allItemId = DB::table('a_std_tool_item_rel')->select('testitem_id')
            ->where('tool_id',$sample_info->tool_id)->where('ishide',0)
            ->groupBy('testitem_id')
            ->get()->map(function ($value) {
                return (array)$value;
            })->toArray();
        if($allItemId){
            $allItemId_arr = array_column($allItemId,'testitem_id');
        }
        //加载模板类
        $template = new \PhpOffice\PhpWord\TemplateProcessor($template_file);
        //为模板中的变量赋值
        $template->setValues($values);

        //审核批准编制人名章
        if($sample_info->tester_names){
            $test_arr = explode('，',$sample_info->tester_names);
            $shen_man = isset($test_arr[0])?$test_arr[0]:'';
            $bian_man = isset($test_arr[1])?$test_arr[1]:'';
        }
        $signs = [
            'pi_man'=>"storage/images/managers/展飞.png",
            'shen_man'=>"storage/images/managers/{$shen_man}.png",
            'bian_man'=>"storage/images/managers/{$bian_man}.png",
        ];
        foreach ($signs as $var => $sign) {
            file_exists($sign) ? $template->setImageValue($var, ["path" => $sign, "height" => 50]) : '';
        }

        //检验结果汇总
        $item_info_item_arr = [];       //当前标准下的全部试验项目id
        $item_info = DB::table('a_item_data as i')
            ->leftJoin('a_testitem as t','t.id','=','i.item_id')
            ->select('i.*','t.name')
            ->where('sample_info_id',$sample_id)->get();
        $rows = count($item_info);
        $template->cloneRow('item_id',$rows);
        foreach($item_info as $key=>$val){
            $item_info_item_arr[] = $val->item_id;
            $no = $key+1;
            $template->setValue("item_id#".$no,$no);
            $template->setValue("item_name#".$no,$val->name);
            $template->setValue("item_result#".$no,'详见报告正文');
            $resmsg = self::$resCode[$val->res];
            $template->setValue("item_res#".$no,$resmsg);
        }
        //报告正文-外观检查
        $waiguanArr = [];
        $waiguan = DB::table('a_item_data')->select('res','item_id')->where('sample_info_id',$sample_id)->whereIn('item_id',[61,84])->first();
        if($waiguan) {
            $waiguanyaoqiu = DB::table('a_std_tool_item_rel')->where('std_id',$sample_info->std_id)->where('tool_id',$sample_info->tool_id)->where('testitem_id',$waiguan->item_id)->first();
            $waiguanArr = [
                'wai_no' => 1,
                'wai_bar_code' => $sample_info->self_num,
                'wai_yaoqiu' => $waiguanyaoqiu->jishu_yaoqiu,
                'wai_item_res' => self::$resCode[$waiguan->res],
                'wai_conclusion' => self::$resCode[$waiguan->res],
            ];
            //外观检查赋值
            #dd($waiguanArr);
            $template->setValues($waiguanArr);
        }
        //报告正文-试验数据
        $arr_item_id = $arr_item_id = explode(',', $sample_info->item_ids);
        //拼装试验数据
        $item_data = DB::table('a_item_data as i')
            ->leftJoin('a_contract_gaiyao as c','c.id','=','i.contract_gaiyao_id')
            ->select('i.*','c.std_id','c.tool_id','c.class_id','c.vol_id')
            ->where('i.sample_info_id',$sample_id)->where('i.item_id','!=',61)->get();
        foreach($item_data as $ikey=>$val){
            $item_res = DB::table('a_std_tool_item_rel')->select('id', 'testitem_id', 'pos_start', 'pos_end','line_num')->where([['std_id', '=', $val->std_id], ['tool_id', '=', $val->tool_id],['testitem_id','=',$val->item_id]])->first();
            $item_data_arr["bar{$item_res->testitem_id}no"] = 1;
            $item_data_arr["bar{$item_res->testitem_id}code"] = $sample_info->self_num;
            $item_data_arr["next{$item_res->testitem_id}time"] = $sample_info->next_time;
            $item_data_arr[$item_res->pos_start.$item_res->testitem_id.$item_res->pos_end] = self::$resCode[$val->res];
            //试验数据
            $key_data = DB::table('a_testdata_key')
                ->select('id', 'item_id', 'pos_start', 'pos_end', 'std_tool_item_rel_id', 'line_num')
                ->where('std_tool_item_rel_id', $item_res->id)
                ->where([['pos_start', '!=', ''], ['pos_end', '!=', '']])
                ->get();
            foreach ($key_data as $kdKey => $vvv2) {
                $val_testdata = DB::table('a_input_data')->where([['sample_info_id', '=', $sample_id], ['testdata_key_id', '=', $vvv2->id]])->value('val');
                $item_data_arr[$vvv2->pos_start.$item_res->testitem_id.$vvv2->pos_end] = $val_testdata;
            }
            //种类
            if($val->class_id){
                $classInfo = DB::table('a_voltage_class as v')
                    ->leftJoin('a_excel_pos as e','v.std_tool_rel_id','=','e.std_tool_rel_id')
                    ->select('v.val','e.class1','e.class2')->where('v.id',$val->class_id)->where('e.is_default',1)->first();
                $item_data_arr[$classInfo->class1.$item_res->testitem_id.$classInfo->class2] = $classInfo->val;
            }
            //电压
            if($val->vol_id){
                $volInfo = DB::table('a_voltage_class as v')
                    ->leftJoin('a_excel_pos as e','v.std_tool_rel_id','=','e.std_tool_rel_id')
                    ->select('v.val','e.voltage1','e.voltage2')->where('v.id',$val->vol_id)->where('e.is_default',1)->first();
                $item_data_arr[$volInfo->voltage1.$item_res->testitem_id.$volInfo->voltage2] = $volInfo->val;
            }
        }
        #dd($item_data_arr);
        $template->setValues($item_data_arr);

        //后删除模块-循环删除
        $diff_itemId = array_diff($allItemId_arr,$item_info_item_arr);
        if($diff_itemId){
            foreach($diff_itemId as $dkey=>$dval){
                $template->deleteBlock("item_{$dval}");
            }
        }
        //将无值的变量置空
        $emptyVars = $template->getVariables();
        foreach ($emptyVars as $emptyVar) {
            $template->setValue($emptyVar,'');
        }
        #dd($template);
        //保存目录
        return $this->saveDown($template,$sample_info);
    }

    private function saveDown($templateProcessor,$sample_info){
        // dd($sample_info);
        $disk = $this->disk;
        $storeFile = $this->storeFile;
        // dd($storeFile);
        try{
            $disk->put($storeFile,''); //创建路径
            $templateProcessor->saveAs($disk->path($storeFile));
            if($this->download){
                return $disk->download($storeFile);
            }
        }catch(Exception $e){
            $disk->delete($storeFile);
        }

        //$filename = iconv("utf-8","gb2312",$sample_info->bar_code);
        //header("Content-type: application/vnd.ms-word");
        //header("Content-Disposition:attachment;filename=".$filename.".docx");
        //header('Cache-Control: max-age=0');
        //$templateProcessor->saveAs("php://output");
        //exit;
    }


}
